using UnityEngine;

namespace Dream.Player
{
    public class CharacterMovement : MonoBehaviour
    {
        public float moveSpeed = 5f; // 角色移动速度
        public float sprintSpeed = 10f; //冲刺速度

        [SerializeField] private BoxCollider2D touchCollider; //检查玩家正前方交互的Collider

        private Vector2 colliderOffset = new(0, 0); //碰撞盒的偏移

        private bool isSprinting; //检查是否处于冲刺状态
        private Vector2 movement; // 存储移动向量

        private Rigidbody2D rb; // 角色的Rigidbody2D组件

        private void Start()
        {
            // 获取Rigidbody2D组件
            if (rb == null) rb = GetComponent<Rigidbody2D>();
            if (rb == null) rb = transform.parent.GetComponent<Rigidbody2D>();

            var colliders = transform.parent.GetComponents<BoxCollider2D>();
            touchCollider = colliders[1]; //获取对应的第二个
        }

        private void Update()
        {
            // 获取水平（Horizontal）和垂直（Vertical）输入
            var moveX = Input.GetAxisRaw("Horizontal");
            var moveY = Input.GetAxisRaw("Vertical");

            // 设置移动向量
            movement = new Vector2(moveX, moveY).normalized; // 归一化向量以确保匀速移动

            // 检测是否按下冲刺键（例如：左Shift）
            if (Input.GetKeyDown(KeyCode.K))
                isSprinting = true;
            else if (Input.GetKeyUp(KeyCode.K)) isSprinting = false;
        }

        private void FixedUpdate()
        {
            // 在FixedUpdate中应用移动，以确保物理计算的一致性
            MoveCharacter();
            // 更新碰撞盒的偏移
            UpdateColliderOffset();
        }

        private void UpdateColliderOffset()
        {
            // 根据输入同步更新碰撞盒的偏移
            if (movement.x != 0 && movement.y == 0)
            {
                colliderOffset.x = movement.x;
                colliderOffset.y = 0;
            }
            else if (movement.x == 0 && movement.y != 0)
            {
                colliderOffset.x = 0;
                colliderOffset.y = movement.y;
            }

            touchCollider.offset = colliderOffset;
        }


        private void MoveCharacter()
        {
            // 使用Rigidbody2D移动角色
            var currentSpeed = isSprinting ? sprintSpeed : moveSpeed;
            rb.MovePosition(rb.position + movement * currentSpeed * Time.fixedDeltaTime);
        }
    }
}